package com.xzz.window;

import java.util.HashMap;

/**
 * @author: hhz
 * @create: 2021-12-24 17:04
 * 567. 字符串的排列
 * 给你两个字符串s1和s2 ，写一个函数来判断 s2 是否包含 s1的排列。如果是，返回 true ；否则，返回 false 。
 *
 * 换句话说，s1 的排列之一是 s2 的 子串 。

 **/
public class CheckInclusion {
    public static void main(String[] args) {
        System.out.println(checkInclusion("abcdxabcde","abcdeabcdx"));
    }
    public static boolean checkInclusion(String s1, String s2) {
        HashMap<Character,Integer> window = new HashMap<>();
        HashMap<Character,Integer> need = new HashMap<>();
        for (int i = 0; i < s1.length(); i++) {
            need.put(s1.charAt(i),need.getOrDefault(s1.charAt(i),0)+1);
        }
        int left = 0 ;
        int right = 0;
        int needNum = 0;
        while (right < s2.length()) {
            char c = s2.charAt(right);
            right++;
            if(need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0)+1);
                if(window.get(c).equals(need.get(c))){
                    needNum++;
                }
            }
            while (right-left >= s1.length()){
                if(needNum == need.size()){
                    return true;
                }
                char d = s2.charAt(left);
                left++;
                if(need.containsKey(d)){
                    if(window.get(d).equals(need.get(d))){
                        needNum--;
                    }
                    window.put(d,window.getOrDefault(d,0)-1);
                }

            }
        }
        return false;
    }

}
